<template>
  <div class="header"> <!-- <audio id="music" src="https://milk-1256444651.cos.ap-chengdu.myqcloud.com/music/70090.mp3" controls="controls"></audio> -->
    <!-- <a-player :music="songList" :showlrc="3" :narrow="false" theme="#b7daff" mode="circulation" v-if="flag" listmaxheight='96px' ref="player"></a-player> -->

    <!-- 折叠按钮 -->
    <div class="collapse-btn" @click="collapseChage">
      <i class="el-icon-menu"></i>
    </div>
    <div class="logo">后台管理系统</div>
    <div style="display: inline-block;line-height: 70px;">
      <span style="font-size: 16px;padding-right: 20px">门店名称：{{admininfo.shopName}}</span>
      <span style="font-size: 16px;">门店地址：{{admininfo.shopAddress}}</span>
      <!-- <img src="../../../static/img/img.jpg" alt=""> -->
    </div>

    <div class="header-right">
      <div class="header-user-con">
        <!-- 全屏显示 -->
        <div class="btn-fullscreen" @click="handleFullScreen">
          <el-tooltip effect="dark" :content="fullscreen?`取消全屏`:`全屏`" placement="bottom">
            <i class="el-icon-rank"></i>
          </el-tooltip>
        </div>
        <!-- 消息中心 -->
                <!-- <div class="btn-bell">
                    <el-tooltip effect="dark" :content="message?`有${message}条未读消息`:`消息中心`" placement="bottom">
                        <router-link to="/order">
                            <i class="el-icon-bell"></i>
                        </router-link>
                    </el-tooltip>
                    <span class="btn-bell-badge" v-if="message"></span>
                  </div> -->
                  <!-- 用户头像 -->
                  <div class="user-avator"><img :src="admininfo.a_img"></div>
                  <!-- 用户名下拉菜单 -->
                  <el-dropdown class="user-name" trigger="click" @command="handleCommand">
                    <span class="el-dropdown-link">
                      {{admininfo.a_name}} <i class="el-icon-caret-bottom"></i>
                    </span>
                    <el-dropdown-menu slot="dropdown">
                       <!--  <a href="http://blog.gdfengshuo.com/about/" target="_blank">
                            <el-dropdown-item>关于作者</el-dropdown-item>
                          </a> -->
                        <!-- <a href="https://github.com/lin-xin/vue-manage-system" target="_blank">
                            <el-dropdown-item>项目仓库</el-dropdown-item>
                          </a> -->
                          <el-dropdown-item divided command="upself">修改个人资料</el-dropdown-item>
                          <el-dropdown-item divided command="upshop">修改门店信息</el-dropdown-item>
                          <el-dropdown-item divided command="loginout">退出登录</el-dropdown-item>

                        </el-dropdown-menu>
                      </el-dropdown>
                    </div>
                  </div>


                  <!-- 修改个人资料 -->

                  <el-dialog title="修改个人资料" :visible.sync="centerDialogVisible" width="30%" center>
                   <el-form ref="form" label-width="100px">
                    <el-form-item label="管理员名称">
                      <el-input v-model="admininfo.a_name"></el-input>
                    </el-form-item>
                    <el-form-item label="头像">
                     <el-upload class="avatar-uploader usermig" :action='$gretUrl+"admin/good/upimg"' :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                      <img v-if="admininfo.a_img" :src="admininfo.a_img" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                  </el-form-item>

                </el-form>

                <span slot="footer" class="dialog-footer">
                  <el-button @click="quit">取 消</el-button>
                  <el-button type="primary" @click="save">确 定</el-button>
                </span>
              </el-dialog>

              <!-- 修改门店信息 -->

              <el-dialog title="修改门店信息" :visible.sync="shopDialogVisible" width="600px" center>
               <el-form ref="form" label-width="100px">
                <el-form-item label="门店名称">
                  <el-input v-model="admininfo.shopName"></el-input>
                </el-form-item>
                <el-form-item label="门店电话">
                  <el-input v-model="admininfo.shopPhone"></el-input>
                </el-form-item>
                <el-form-item label="WIFI密码">
                  <el-input v-model="admininfo.wifi"></el-input>
                </el-form-item>
                <el-form-item label="营业时间">
                 <el-time-picker is-range value-format="HH:mm" v-model="admininfo.shop_time" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围">
                  <!--  <el-time-picker  v-model="startTime" :picker-options="{ selectableRange: '06:30:00 - 20:30:00'}" placeholder="起始时间"></el-time-picker>
                   <el-time-picker arrow-control v-model="endTime" :picker-options="{
                    selectableRange: '18:30:00 - 20:30:00'
                  }" -->
                  placeholder="结束时间">
                </el-time-picker>
              </el-time-picker>
            </el-form-item>
            <el-form-item label="门店地址选取">
             <div class="amap-page-container">
              <el-amap-search-box class="search-box" :search-option="searchOption" :on-search-result="onSearchResult"></el-amap-search-box>
              <el-amap vid="amapDemo" :center="center" :zoom="zoom" class="amap-demo"  :plugin="plugin"  :events="events">
                <el-amap-marker vid="amapDemo" :position="center" icon="https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png" ></el-amap-marker>
                <el-amap-marker v-for="(marker,index) in markers" :key="index" :position="marker" :events="clickMarker"></el-amap-marker>    
                <!-- :icon=" marker == center ? 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png':'https://webapi.amap.com/theme/v1.3/markers/n/mark_bs.png'"  -->

              </el-amap>
               <!--  <div class="toolbar">
                  position: [{{ admininfo.shopLon }}, {{ admininfo.shopLat }}] address: {{ admininfo.shopAddress }}
                 position: [{{ lng }}, {{ lat }}] address: {{ address }}
               </div> -->
             </div>
           </el-form-item>
           <el-form-item label="门店经度">
            <el-input v-model="admininfo.shopLon"></el-input>
          </el-form-item>
          <el-form-item label="门店纬度">
            <el-input v-model="admininfo.shopLat"></el-input>
          </el-form-item>
          <el-form-item label="门店具体地址">
            <el-input v-model="admininfo.shopAddress"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="shopQuit">取 消</el-button>
          <el-button type="primary" @click="saveInfo">确 定</el-button>
        </span>
      </el-dialog>

    </div>

  </template>
  <script>
    import bus from '../common/bus';
    import GoEasy from '../../../static/js/goeasy.js';
    // import VueAplayer from 'vue-aplayer'
    export default {
      inject:['reload'],
      data() {
        let self = this;
        return {
          collapse: false,
          fullscreen: false,
          name: 'linxin',
          message: 0,
          centerDialogVisible: false,
          shopDialogVisible:false,
          admininfo:JSON.parse(localStorage.getItem('ms_username')),

          markers: [],
          searchOption: {
            city: '广州',
            citylimit: true
          },
            // mapCenter: [113.260782,23.119976],
            zoom: 12,
            // center: [121.59996, 31.197646],
            center: [113.260782,23.119976],
            // center: [self.admininfo.shopLon,self.admininfo.shopLat],
            address: '',
            events: {
              init(o){
                self.map = o;
              },
              click(e) {
                // self.markers = [];
                let { lng, lat } = e.lnglat;
                self.admininfo.shopLon = lng;
                self.admininfo.shopLat = lat;
                self.center = [e.lnglat.lng, e.lnglat.lat];//点击选择新地址为中心点

                // 这里通过高德 SDK 完成。
                var geocoder = new AMap.Geocoder({
                  radius: 1000,
                  extensions: "all"
                });        
                geocoder.getAddress([lng ,lat], function(status, result) {
                  if (status === 'complete' && result.info === 'OK') {
                    if (result && result.regeocode) {
                      self.admininfo.shopAddress = result.regeocode.formattedAddress;
                      self.$nextTick();
                    }
                  }
                });        
              },
            },
            plugin: [
              // "ToolBar",
              // {
              //   pName: "MapType",
              //   defaultType: 0,
              //   events: {
              //     init(o) {
              //       console.log(o);
              //     }
              //   }
              // }
              ],
              clickMarker:{
                click(e){
                  let { lng, lat } = e.target.Uh.position;
                  self.admininfo.shopLon = lng;
                  self.admininfo.shopLat = lat;
                // console.log(e)
                // console.log(lng)
                // console.log(self.markers)
                self.center = [e.target.Uh.position.lng, e.target.Uh.position.lat];


                var geocoder = new AMap.Geocoder({
                  radius: 1000,
                  extensions: "all"
                }); 


                geocoder.getAddress([lng, lat], function(status, result) {
                  if (status === 'complete' && result.info === 'OK') {
                    if (result && result.regeocode) {
                      self.admininfo.shopAddress = result.regeocode.formattedAddress;
                      self.$nextTick();
                    }
                  }
                });

              },

            },
            lng: 0,
            lat: 0

          }
        },
        // components: {
        //     //别忘了引入组件
        //     'a-player': VueAplayer
        //   },
        // async mounted () {
            //异步加载，先加载出player再使用
            // await this.playMusic();
            // let aplayer = this.$refs.player.control;
        //     aplayer.play();
          // },
          created(){
            // this.init()
            // this.playMusic()

          },
        // beforeMount(){
        //     this.playMusic()
        // },
        // computed:{
        //     username(){
        //         let username = JSON.parse(localStorage.getItem('ms_username'))[0]['a_name'];
        //         return username ? username : this.name;
        //     },
        //     userimg(){
        //         let userimg = JSON.parse(localStorage.getItem('ms_username'))[0]['a_img'];
        //         return userimg ? userimg : this.a_img;
        //     }
        // },


        methods:{
          playMusic(){
              // var audio = document.getElementById('music');
              // audio.pause();
              // setTimeout(function () {
              //   audio.play();
              //   // audio.pause();
              //   }, 150);
              // let audio = new Audio('https://pic.ibaotu.com/00/56/52/31Z888piCHeE.mp3')
              let audio = new Audio('./static/music/xiaochengxu_order.mp3')
              audio.play()

            },
            // async init () {
            //   //这边是引入了axios然后使用的get请求的一个音乐列表接口
            //   const getMusicList = url => axios.get(url);
            //   //这边url随大家更改了
            //   let url = '';
            //   let data = await getMusicList(url);
            //   //以下就是这边对请求的一个处理，看接口了
            //   if(data && data.data.showapi_res_code==0){
            //     this.musicList = data.data.showapi_res_body.pagebean.songlist;

            //     for(let i=0;i<=this.musicList.length;i++){
            //       if(i<=9){
            //         let obj={};
            //         //url=>歌曲地址 title=>头部 author=>歌手 pic=>写真图片 lrc=>歌词
            //         //其中url必须有，其他的都是非必须
            //         obj.title = this.musicList[i].songname;
            //         obj.author = this.musicList[i].singername;
            //         obj.url = this.musicList[i].url;
            //         obj.pic = this.musicList[i].albumpic_small;
            //         obj.lrc = this.musicList[i].irl;
            //         //把数据一个个push到songList数组中，在a-player标签中使用 :music="songList" 就OK了
            //         this.songList.push(obj);
            //       }
            //     }
            //     //因为是异步请求，所以一开始播放器中是没有歌曲的，所有给了个v-if不然会插件默认会先生成播放器，导致报错(这个很重要)
            //     this.flag = true;
            //   };
            // }
            init(){
              var that = this
                var audio = document.getElementById('music');
                var goeasy = new GoEasy({
                    // appkey: 'BC-b02a32e9889f4f70be91c1e63f618c38'
                    appkey:"BC-578bc8d2da324359be1fc3f79aabc0dd"    //台铺
                });
                goeasy.subscribe({
                    channel: 'tea_bd',
                    onMessage: function(message){
                        // that.message = that.message++

                        that.playMusic()
                        // that.reload()
                        that.open()
                        // alert('提示：'+message.content);
                       // console.log(message)
                    }
                });

                if(that.$router == '/order'){
                   that.message = 0
                }
              },
              open() {
                this.$notify.success({
                  title: 'Info',
                  message: '你有新的订单来了！！！',
                  showClose: false
                });
              },
            // 用户名下拉菜单选择事件
            handleCommand(command) {
              if(command == 'loginout'){
                localStorage.removeItem('ms_username')
                this.$router.push('/login');
              }
              else if(command == 'upself'){
                this.centerDialogVisible = true
              }
              else if(command == 'upshop'){
                    // this.$router.push('/map')
                    this.shopDialogVisible = true
                  }
                },
            // 侧边栏折叠
            collapseChage(){
              this.collapse = !this.collapse;
              bus.$emit('collapse', this.collapse);
            },
            // 全屏事件
            handleFullScreen(){
              let element = document.documentElement;
              if (this.fullscreen) {
                if (document.exitFullscreen) {
                  document.exitFullscreen();
                } else if (document.webkitCancelFullScreen) {
                  document.webkitCancelFullScreen();
                } else if (document.mozCancelFullScreen) {
                  document.mozCancelFullScreen();
                } else if (document.msExitFullscreen) {
                  document.msExitFullscreen();
                }
              } else {
                if (element.requestFullscreen) {
                  element.requestFullscreen();
                } else if (element.webkitRequestFullScreen) {
                  element.webkitRequestFullScreen();
                } else if (element.mozRequestFullScreen) {
                  element.mozRequestFullScreen();
                } else if (element.msRequestFullscreen) {
                        // IE11
                        element.msRequestFullscreen();
                      }
                    }
                    this.fullscreen = !this.fullscreen;
                  },
                  handleAvatarSuccess(res, file) {
                    console.log(res);
                // this.imageUrl = URL.createObjectURL(file.raw);
                this.admininfo.a_img = res.data.data.src
              },
              beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                  this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                  this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
              },

            //保存资料
            save(){

              this.$axios.post('admin/index/upinfo',{
                aid: this.admininfo.admin_id,
                token: this.admininfo.token,
                a_name: this.admininfo.a_name,
                a_img: this.admininfo.a_img
              }).then((res) => {

               if(res.data.status == 0){
                let storage = JSON.parse(localStorage.ms_username)
                storage.a_name = this.admininfo.a_name
                storage.a_img = this.admininfo.a_img
                localStorage.setItem('ms_username',JSON.stringify(storage))
                this.$message.success(`修改成功`);
              }else if(res.data.status == 3){
               this.$router.push('login') 
             }else{
               this.$message.error(res.data.msg);
             }
             this.centerDialogVisible = false
           })       

            },
            quit(){
                // console.log(JSON.parse(localStorage.getItem('ms_username')))
                this.admininfo.a_img = JSON.parse(localStorage.getItem('ms_username')).a_img;
                this.admininfo.a_name = JSON.parse(localStorage.getItem('ms_username')).a_name;
                this.centerDialogVisible = false
              },
              shopQuit(){
                this.admininfo.shopName = JSON.parse(localStorage.getItem('ms_username')).shopName;
                this.admininfo.shopPhone = JSON.parse(localStorage.getItem('ms_username')).shopPhone;
                this.admininfo.wifi = JSON.parse(localStorage.getItem('ms_username')).wifi;
                
                this.admininfo.shopLat = JSON.parse(localStorage.getItem('ms_username')).shopLat;
                this.admininfo.shopLon = JSON.parse(localStorage.getItem('ms_username')).shopLon;
                this.admininfo.shopAddress = JSON.parse(localStorage.getItem('ms_username')).shopAddress;
                this.shopDialogVisible = false
              },
              addMarker: function() {
                let lng = 113.260782 + Math.round(Math.random() * 1000) / 10000;
                let lat = 23.119976 + Math.round(Math.random() * 500) / 10000;
                this.markers.push([lng, lat]);
                console.log(this.markers)
              },
              onSearchResult(pois) {
                let latSum = 0;
                let lngSum = 0;
                if (pois.length > 0) {
                  pois.forEach(poi => {
                    let {lng, lat} = poi;
                    lngSum += lng;
                    latSum += lat;
                    this.markers.push([poi.lng, poi.lat]);
                  });
                  let center = {
                    lng: lngSum / pois.length,
                    lat: latSum / pois.length
                  };
                  this.center = [center.lng, center.lat];
                }
              },
              saveInfo(){
                // console.log(this.admininfo)
                this.$axios.post('admin/index/shopup',{
                  aid: this.admininfo.admin_id,
                  token: this.admininfo.token,
                  shop_name: this.admininfo.shopName,
                  shop_phone: this.admininfo.shopPhone,
                  wifi: this.admininfo.wifi,
                  shop_time: this.admininfo.shop_time,
                  shop_lat: this.admininfo.shopLat,
                  shop_lon: this.admininfo.shopLon,
                  shop_address: this.admininfo.shopAddress
                }).then((res) => {

                 if(res.data.status == 0){
                  let storage = JSON.parse(localStorage.ms_username)
                  storage.shopName = this.admininfo.shopName
                  storage.shopPhone = this.admininfo.shopPhone
                  storage.shop_time = this.admininfo.shop_time
                  storage.wifi = this.admininfo.wifi
                  storage.shopLat = this.admininfo.shopLat
                  storage.shopLon = this.admininfo.shopLon
                  storage.shopAddress = this.admininfo.shopAddress

                  localStorage.setItem('ms_username',JSON.stringify(storage))
                  this.$message.success(`修改成功`);
                }else if(res.data.status == 3){
                 this.$router.push('login') 
               }else{
                 this.$message.error(res.data.msg);
               }
               this.shopDialogVisible = false
             })
              }

            },
            mounted(){
              if(document.body.clientWidth < 1500){
                this.collapseChage();
              }
            },


          }
        </script>
        <style scoped>
        .header {
          position: relative;
          box-sizing: border-box;
          width: 100%;
          height: 70px;
          font-size: 22px;
          color: #fff;
        }
        .collapse-btn{
          float: left;
          padding: 0 21px;
          cursor: pointer;
          line-height: 70px;
        }
        .header .logo{
          float: left;
          width:250px;
          line-height: 70px;
        }
        .header-right{
          float: right;
          padding-right: 50px;
        }
        .header-user-con{
          display: flex;
          height: 70px;
          align-items: center;
        }
        .btn-fullscreen{
          transform: rotate(45deg);
          margin-right: 5px;
          font-size: 24px;
        }
        .btn-bell, .btn-fullscreen{
          position: relative;
          width: 30px;
          height: 30px;
          text-align: center;
          border-radius: 15px;
          cursor: pointer;
        }
        .btn-bell-badge{
          position: absolute;
          right: 0;
          top: -2px;
          width: 8px;
          height: 8px;
          border-radius: 4px;
          background: #f56c6c;
          color: #fff;
        }
        .btn-bell .el-icon-bell{
          color: #fff;
        }
        .user-name{
          margin-left: 10px;
        }
        .user-avator{
          margin-left: 20px;
        }
        .user-avator img{
          display: block;
          width:40px;
          height:40px;
          border-radius: 50%;
        }
        .el-dropdown-link{
          color: #fff;
          cursor: pointer;
        }
        .el-dropdown-menu__item{
          text-align: center;
        }
        #music{
          position: absolute;
          top:-100px;
          /*top: 0;*/
        }
        .el-upload{
          min-width: auto !important;
          height: auto !important;
        }
        .avatar{
          width: 100%;
          height:100%;
          border-radius: 100%;
        }

        /*地图*/
        .amap-demo {
          height: 300px;
        }

        .search-box {
          position: absolute;
          top: 25px;
          left: 20px;
        }
        .toolbar{
          margin-top: 15px;
        }
        .amap-page-container {
          position: relative;
        }
        .el-vue-amap{
          height: 500px !important;
        }
      </style>
